package br.com.portalaberto.bd;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import javax.microedition.lcdui.List;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotOpenException;

/**
 * Classe utilitaria para persistencia
 *
 * @author Elaine Cristina e Lucas Vieira
 * @version 1.0
 */
public class Persistencia {

    private static Persistencia instancia = null;
    private RecordStore rsRecordes;


    public static Persistencia getInstancia() {
        if (instancia == null) {
            instancia = new Persistencia();
        }
        return instancia;
    }

    public Persistencia() {
    }

    //metodo a ser chamado no destroy app
    public void fecharRecordStores() {


            try {
                rsRecordes.closeRecordStore();
            } catch (RecordStoreException ex) {
                ex.printStackTrace();
            }

    }

    public void abrirRecordStores() {



            try {
                rsRecordes = RecordStore.openRecordStore("recordes_pollme", true);
            } catch (RecordStoreException ex) {
                ex.printStackTrace();
            }

    }

    public int cadastrarRecorde(String recordista, int recorde) {
        abrirRecordStores();
        int resultado = 0;
        if (recordista == null || recordista.equals("")) {
            recordista = "NDA";
        } else if (recordista.length() < 3) {
            if (recordista.length() == 2) {
                recordista += "Z";
            } else {
                recordista += "ZZ";
            }
        } else {
            String rec = recordista.substring(0, 3).toUpperCase() + "-" + recorde;
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                PrintStream ps = new PrintStream(baos);
                ps.print(rec);
                int total = rsRecordes.getNumRecords();
                if (total < 5) {
                    resultado = rsRecordes.addRecord(baos.toByteArray(), 0, baos.size());
                } else if (total >= 5 && recorde > this.getMenorRecorde()[0]) {
                    rsRecordes.setRecord((this.getMenorRecorde()[0]+1), baos.toByteArray(), 0, baos.size());
                    resultado = this.getMenorRecorde()[1];
                }
            } catch (RecordStoreNotOpenException e) {
                e.printStackTrace();
            } catch (RecordStoreFullException e) {
                e.printStackTrace();
            } catch (RecordStoreException e) {
                e.printStackTrace();
            }
        }
        fecharRecordStores();
        return resultado;
    }

    private String[] bubbleSort(String[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - i - 1; j++) {
                int num1 = Integer.parseInt(a[j].substring(a[j].indexOf("-") + 1, a[j].length()));
                int num2 = Integer.parseInt(a[j + 1].substring(a[j + 1].indexOf("-") + 1, a[j + 1].length()));
                if (num1 > num2) {
                    swap(a, j, j + 1);
                }
            }
        }
        String[] retorno = new String[a.length];
        int num = 0;
        for (int i = (a.length - 1); i >= 0; i--) {
            retorno[num] = a[i];
            num++;
        }
        return retorno;
    }

    private void swap(String[] a, int i, int j) {
        String temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    public String[] listarRecordesOrdenados() {
        abrirRecordStores();
        String[] recordes = listar(this.retornaRecordes());
        if(recordes.length > 1)
            recordes = bubbleSort(recordes);
        fecharRecordStores();
        return recordes;
    }

    public int[] getMenorRecorde() {
        String[] recordes = listar(this.retornaRecordes());
        int[] aux = new int[recordes.length];
        if(recordes.length == 0){
            int[] retorno = {0,0};
            return retorno;
        }
        for (int i = 0; i < recordes.length; i++) {
            aux[i] = Integer.parseInt(recordes[i].substring(recordes[i].indexOf("-") + 1, recordes[i].length()));
        }
        int menorValor = aux[0];
        int menorIndex = 0;
        for (int i = 0; i < recordes.length; i++) {
            if (aux[i] < menorValor) {
                menorValor = aux[i];
                menorIndex = i;
            }
        }
        int[] retorno = {menorValor, menorIndex};
        return retorno;
    }


    public RecordEnumeration retornaRecordes() {
        RecordEnumeration re = null;
        try {
            re = rsRecordes.enumerateRecords(null, null, false);
        } catch (RecordStoreNotOpenException e) {
            e.printStackTrace();
        }
        return re;
    }

    public String[] listar(RecordEnumeration re) {
        List lista = new List("", List.IMPLICIT);
        while (re.hasNextElement()) {
            byte[] est = null;
            try {
                est = re.nextRecord();
            } catch (InvalidRecordIDException e) {
                e.printStackTrace();
            } catch (RecordStoreNotOpenException e) {
                e.printStackTrace();
            } catch (RecordStoreException e) {
                e.printStackTrace();
            }
            String str = null;
            str = new String(est);
            if(str != null){
                lista.append(str, null);
            }
        }
        re.destroy();
        String[] arString = new String[lista.size()];
        for (int i = 0; i < lista.size(); i++) {
            arString[i] = lista.getString(i);
        }
        return arString;
    }

    public void limparRecordes() {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            ps.print("NDA-000");
            abrirRecordStores();
            if (rsRecordes != null) {
                for (int i = 1; i <= rsRecordes.getNumRecords(); i++) {
                    rsRecordes.setRecord(i, baos.toByteArray(), 0, baos.size());
                }
            }
            fecharRecordStores();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}